package com.nova.bluetooth.helpUtils;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.FileUtils;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

public class FileUtil {
    public final static String FILE_TAG = "/rich_editor";
    public static final String DOCUMENTS_DIR = "documents";

    /**
     * android10.0 获取视频路径转换
     *
     * @param url content://media/external/file/366086
     * @return 返回最终的路径：/storage/emulated/0/tencent/MicroMsg/WeiXin/1583552860791.mp4
     */
    public static String getRealPathFromUri(Context context, String url) {
        Uri contentUri = Uri.parse(url);
        Cursor cursor = null;
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    /**
     * 获取文件大小
     *
     * @param path
     * @return
     */
    public static long getFileSize(String path) {
        File file = new File(path);
        return getFileSize(file);
    }

    public static long getFileSize(@NonNull File file) {
        if (!file.exists()) {
            return -1;
        }
        return file.length();
    }

    public static int getFileSizeKB(@NonNull File file) {
        return (int) Math.round((double) getFileSize(file) / 1024.0);
    }

    /**
     * 格式化文件大小，返回KB,MB,GB,TB
     *
     * @param fileSizeKB
     * @return
     */
    public static String formatFileSize(final int fileSizeKB) {
        if (fileSizeKB <= 0) {
            return "0KB";
        }

        final String[] units = new String[]{"KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(fileSizeKB) / Math.log10(1024));

        DecimalFormat decimalFormat = new DecimalFormat("#,##0.#");
        return decimalFormat.format(fileSizeKB / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

    /**
     * 检查文件是否符合要求
     *
     * @param filePath
     * @return
     */
    public static boolean isFilePathValid(String filePath) {
        return filePath != null
                && (filePath.endsWith(".wav")
                || filePath.endsWith(".mp3")||
                filePath.endsWith(".m4a"));
    }

    /**
     * 检查文件是否符合要求
     *
     * @param filePath
     * @return
     */
    public static boolean isFilePathSizeValid(String filePath) {
        return filePath != null
                && getFileSize(filePath) <= 1024 * 1024 * 50;
    }

    /**
     * 获取文件后缀
     *
     * @param filePath
     * @return
     */
    public static String getFileType(String filePath) {
        int lastDotIndex = filePath.lastIndexOf('.');
        if (lastDotIndex >= 0 && lastDotIndex < filePath.length() - 1) {
            String fileExtension = filePath.substring(lastDotIndex + 1);
            return fileExtension;
        } else {
            return "null";
        }
    }


    /**
     * content://返回真实路径
     *
     * @param context
     * @param uri
     * @return
     */
    public static String getPath(final Context context, final Uri uri) {
        String filePath = uri.getPath();
        //这是一个直接的文件系统路径
        if (new File(filePath).exists()) {
            return filePath;
        }

        String getWxContentPath = uriToFile(context, uri);
        if(!TextUtils.isEmpty(getWxContentPath)) {
            return getWxContentPath;
        }
        // DocumentProvider
        if (DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            } else if (isDownloadsDocument(uri)) { // DownloadsProvider
                final String id = DocumentsContract.getDocumentId(uri);
                if (id != null && id.startsWith("raw:")) {
                    return id.substring(4);
                }
                String[] contentUriPrefixesToTry = new String[]{
                        "content://downloads/public_downloads",
                        "content://downloads/my_downloads"
                };
                for (String contentUriPrefix : contentUriPrefixesToTry) {
                    try {
                        Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix),
                                Long.valueOf(id));

                        String path = getDataColumn(context, contentUri, null, null);
                        if (path != null && !path.equals("")) {
                            return path;
                        }
                    } catch (Exception e) {
                    }
                }
                // path could not be retrieved using ContentResolver, therefore copy file to
                // accessible cache using streams
                String fileName = getFileName(context, uri);
                File cacheDir = getDocumentCacheDir(context);
                File file = generateFileNamePlus(fileName, cacheDir);
                String destinationPath = null;
                if (file != null) {
                    destinationPath = file.getAbsolutePath();
                    saveFileFromUri(context, uri, destinationPath);
                }
                return destinationPath;
            } else if (isMediaDocument(uri)) { // MediaProvider
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                } else {
                    //其它类型
                    contentUri = MediaStore.Files.getContentUri("external");
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) { // MediaStore (and general)
            return getDingTalkFilePath(context, uri);
//            if (uri.toString().startsWith("content://com.alibaba.android.rimet")){
//                return getDingTalkFilePath(context, uri);
//            }else {
//                return getDataColumn(context, uri, null, null);
//            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) { // File
            return uri.getPath();
        }

        return null;
    }





    public static String getDingTalkFilePath(Context context, Uri uri) {
        String fileName = getFileName(context, uri);
        if (fileName == null) {
            return null;
        }

        File cacheDir = getDocumentCacheDir(context);
        File file = generateFileNamePlus(fileName, cacheDir);
        if (file == null) {
            return null;
        }

        String destinationPath = file.getAbsolutePath();
        saveFileFromUri(context, uri, destinationPath);
        return destinationPath;
    }



    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }


    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs
                    , null);
            if (cursor != null && cursor.moveToFirst()) {
                final int columnIndex = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(columnIndex);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    public static String getFileName(@NonNull Context context, Uri uri) {
        String mimeType = context.getContentResolver().getType(uri);
        String filename = null;

        if (mimeType == null) {
            String path = getPath(context, uri);
            if (path == null) {
                filename = getName(uri.toString());
            } else {
                File file = new File(path);
                filename = file.getName();
            }
        } else {
            Cursor returnCursor = context.getContentResolver().query(uri, null,
                    null, null, null);
            if (returnCursor != null) {
                int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                returnCursor.moveToFirst();
                filename = returnCursor.getString(nameIndex);
                returnCursor.close();
            }
        }

        return filename;
    }

    public static String getName(String filename) {
        if (filename == null) {
            return null;
        }
        int index = filename.lastIndexOf('/');
        return filename.substring(index + 1);
    }


    public static File getDocumentCacheDir(@NonNull Context context) {
        File dir = new File(context.getCacheDir(), DOCUMENTS_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        return dir;
    }


    private static void saveFileFromUri(Context context, Uri uri, String destinationPath) {
        InputStream is = null;
        BufferedOutputStream bos = null;
        try {
            is = context.getContentResolver().openInputStream(uri);
            bos = new BufferedOutputStream(new FileOutputStream(destinationPath, false));
            byte[] buf = new byte[1024];
            is.read(buf);
            do {
                bos.write(buf);
            } while (is.read(buf) != -1);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
                if (bos != null) bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Nullable
    public static File generateFileNamePlus(@Nullable String name, File directory) {
        if (name == null) {
            return null;
        }

        File file = new File(directory, name);

        if (file.exists()) {
            String fileName = name;
            String extension = "";
            int dotIndex = name.lastIndexOf('.');
            if (dotIndex > 0) {
                fileName = name.substring(0, dotIndex);
                extension = name.substring(dotIndex);
            }

            int index = 0;

            while (file.exists()) {
                index++;
                name = fileName + '(' + index + ')' + extension;
                file = new File(directory, name);
            }
        }

        try {
            if (!file.createNewFile()) {
                return null;
            }
        } catch (IOException e) {
            return null;
        }

        return file;
    }


    //通过微信URI解析文件地址
    public static String uriToFile(Context context, Uri uri) {
        try {
            File file = null;
            if (uri == null) return null;
            //获得ContentResolver，用于访问其它应用数据
            ContentResolver resolver = context.getContentResolver();
            //从路径中提取文件名+文件扩展名
            String displayName = getFileName(context,uri);
            //解析微信文件路径
            InputStream is = null;
            FileOutputStream fos = null;
            if (uri.toString().toLowerCase().startsWith("content://com.tencent.mm.external.fileprovider/")
                    || uri.toString().toLowerCase().startsWith("content://0@com.tencent.mm.external.fileprovider/")) {
                try {
                    is = resolver.openInputStream(uri);
                    File cache = new File(context.getCacheDir().getAbsolutePath(), displayName);
                    fos = new FileOutputStream(cache);
                    //android.os.FileUtils不是工具类，是Android的SDK方法
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        FileUtils.copy(is, fos);
                    }else{
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = is.read(buffer)) != -1) {
                            fos.write(buffer, 0, bytesRead);
                        }
                    }
                    file = cache;
                    return file.toString();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    // 关闭输入流和输出流
                    try {
                        if (fos != null) {
                            fos.close();
                        }
                        if (is != null) {
                            is.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据文件路径获取文件名
     * @param filePath
     * @return
     */
    public static String extractFileName(String filePath) {
        // 找到最后一个斜杠的位置
        int lastIndexOfSlash = filePath.lastIndexOf("/");

        // 如果找到斜杠，从该位置开始提取文件名；否则，返回原始路径
        if (lastIndexOfSlash != -1) {
            return filePath.substring(lastIndexOfSlash + 1);
        } else {
            return filePath;
        }
    }

    public static boolean renameFile(String oldFilePath, String newFileName) {
        try {
            // 创建File对象表示原始文件
            File oldFile = new File(oldFilePath);

            // 获取原始文件的父目录
            String parentDirectory = oldFile.getParent();

            // 创建File对象表示新文件路径
            File newFile = new File(parentDirectory, newFileName);

            // 调用renameTo()方法实现文件重命名
            return oldFile.renameTo(newFile);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
